from PySide6.QtWidgets import QDialog, QMessageBox
from PySide6.QtCore import Signal, QCoreApplication
from ui.source_ui import Ui_SourceSettingsDialog
# from drivers.fake_source_meter import SourceMeterController  # 可替换为真实 source_meter
from drivers.source_meter import SourceMeterController  # 可替换为真实 source_meter
from utils.config_manager import ConfigManager
from utils.log_manager import logger

class SourceController(QDialog):
    settings_applied = Signal()  # 添加信号

    def __init__(self, parent=None, source=None):
        super().__init__(parent)
        self.ui = Ui_SourceSettingsDialog()
        self.ui.setupUi(self)

        self.config = ConfigManager()
        self.settings = self.config.get_source_config()

        self.source = source if source is not None else SourceMeterController()

        self._load_to_ui()
        self._bind_signals()

    def _load_to_ui(self):
        """从配置加载设置到界面"""
        self.ui.lineEdit_set.setText(str(self.settings['voltage']))
        self.ui.lineEdit_limit.setText(str(self.settings['limit']))
        self.ui.spin_samples.setValue(self.settings['samples'])
        self.ui.spin_interval.setValue(self.settings['interval'])

    def showEvent(self, event):
        # 每次打开窗口都重新加载配置，并刷新连接状态
        self.settings = self.config.get_source_config()
        self._load_to_ui()

        # 自动更新连接状态标签
        if self.source and self.source.is_connected():
            msg = QCoreApplication.translate("SourceController", "设备已连接: {addr}")
            self.ui.label_status_value.setText(msg.format(addr=self.source.address))
        else:
            msg = QCoreApplication.translate("SourceController", "设备未连接")
            self.ui.label_status_value.setText(msg)

        super().showEvent(event)

    def _bind_signals(self):
        self.ui.btn_connect.clicked.connect(self._connect_device)
        self.ui.btn_disconnect.clicked.connect(self._disconnect_device)
        self.ui.btn_apply.clicked.connect(self._apply_settings)
        self.ui.btn_cancel.clicked.connect(self.reject)

    def _connect_device(self):
        try:
            self.source.connect()
            msg = QCoreApplication.translate("SourceController", "设备已连接: {addr}")
            self.ui.label_status_value.setText(msg.format(addr=self.source.address))
        except Exception as e:
            title_fail = QCoreApplication.translate("SourceController", "连接失败")
            msg_off = QCoreApplication.translate("SourceController", "设备未连接")
            QMessageBox.critical(self, title_fail, str(e))
            self.ui.label_status_value.setText(msg_off)

    def _disconnect_device(self):
        if self.source.is_connected():
            self.source.disconnect()
            msg_off = QCoreApplication.translate("SourceController", "设备未连接")
            self.ui.label_status_value.setText(msg_off)
        else:
            msg_log = QCoreApplication.translate("SourceController", "⚠️ 设备未连接，无需断开")
            logger.log(msg_log)

    def _apply_settings(self):
        try:
            voltage = float(self.ui.lineEdit_set.text())
            limit = float(self.ui.lineEdit_limit.text())
            samples = self.ui.spin_samples.value()
            interval = self.ui.spin_interval.value()

            # 保存设置到配置文件
            self.settings.update({
                'voltage': voltage,
                'limit': limit,
                'samples': samples,
                'interval': interval
            })
            self.config.set_source_config(self.settings)

            # 如果已连接则应用到设备
            if self.source.is_connected():
                # self.source.apply_settings(voltage, limit, samples, interval)
                # 设置为电压源、设置电压、设置限流
                # self.source.set_mode_voltage('a')
                # self.source.set_output_value(voltage, 'a')
                # self.source.set_protect_current(limit, 'a')
                self.apply_source_settings()
                
                title_ok = QCoreApplication.translate("SourceController", "成功")
                msg_ok = QCoreApplication.translate("SourceController", "设置已应用并更新到设备")
                QMessageBox.information(self, title_ok, msg_ok)
            else:
                title_tip = QCoreApplication.translate("SourceController", "提示")
                msg_unconnected = QCoreApplication.translate("SourceController", "设备未连接，配置已保存但未生效")
                QMessageBox.warning(self, title_tip, msg_unconnected)
            self.settings_applied.emit()  # 应用后发出信号
            self.accept()  # 自动关闭窗口
        except Exception as e:
            title_fail = QCoreApplication.translate("SourceController", "设置失败")
            QMessageBox.critical(self, title_fail, str(e))

    def get_samples(self):
        #执行采样（用于主界面调用）
        #:return: {'samples': [...], 'median': ...}，设备未连接则返回 None
        if not self.source.is_connected():
            msg_log = QCoreApplication.translate("SourceController", "⚠️ 采样失败：源表未连接")
            logger.log(msg_log)
            return None

        return self.source.perform_sampling()

    def apply_source_settings(self, channel='a'):
        """
        从配置文件读取电压、限流参数，设置到源表对应通道。
        """
        try:
            # 重新读取一次配置，确保拿到最新参数
            self.settings = self.config.get_source_config()
            voltage = self.settings['voltage']
            limit = self.settings['limit']

            if not self.source.is_connected():
                raise RuntimeError(QCoreApplication.translate("SourceController", "源表未连接，无法应用设置"))

            # 按要求设置：电压源 -> 设置电压 -> 设置限流
            self.source.set_mode_voltage(channel)
            self.source.set_output_value(voltage, channel)
            self.source.set_protect_current(limit, channel)

            logger.log(QCoreApplication.translate("SourceController", "[{channel}] 成功应用源表设置 V={voltage:.4f}V, Limit={limit:.4f}A").format(
                channel=channel.upper(), voltage=voltage, limit=limit
            ))

        except Exception as e:
            logger.log(QCoreApplication.translate("SourceController", "❌ 应用源表设置失败: {e}").format(e=e))
            raise
